package com.yxd.connector.http;

import com.yxd.logging.SysLogger;
import com.yxd.processor.ServletProcessor;
import com.yxd.processor.StaticResourceProcessor;
import com.yxd.util.RequestInputStream;
import com.yxd.util.ResponseOutputStream;

import java.net.Socket;

/**
 * Created by Administrator on 2016/6/16.
 */
public class HttpProcessor implements Runnable {
    private final Socket socket;
    private HttpConnector httpConnector;
    private HttpRequest request;
    private HttpResponse response;

    public HttpProcessor(HttpConnector httpConnector, Socket socket) {
        this.httpConnector = httpConnector;
        this.socket = socket;
    }

    public void process() {
        Thread thread = new Thread(this);
        thread.start();
    }

    @Override
    public void run() {
        RequestInputStream inputStream = null;
        ResponseOutputStream outputStream = null;
        try {
            inputStream = new RequestInputStream(socket.getInputStream());
            outputStream = new ResponseOutputStream(socket.getOutputStream());
            request = new HttpRequest(inputStream);
            if (request.getProtocol() == null || !request.getProtocol().toLowerCase().equals("http")) {
                return;
            }
            response = new HttpResponse(request, outputStream);

            SysLogger.print("receive a request : " + request.getRequestURI());
            //dispatch
            if (request.getRequestURI().startsWith("/servlet")) {
                ServletProcessor servletProcessor = new ServletProcessor();
                servletProcessor.handle(request, response);
            } else {
                com.yxd.contract.HttpProcessor staticResourceProcessor = new StaticResourceProcessor();
                staticResourceProcessor.handle(request, response);
            }
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
